<template>
  <div class="chat-list">
    <div class="message-area scroll-view" ref="scrollView" @scroll="onScroll">
      <template v-for="(item, index) in messages" :key="item.chatid">
        <chat-message
          :issueData="item.issueData ? item.issueData : []"
          :message="item.data"
          :type="item.type"
          :writing="isWriting(index, item)"
          @question="onQuestion"
          :loading="sending"
        />
      </template>
    </div>
    <chat-send-area ref="sendAreaRef" :loading="sending" @send="sendMessage" @stop="stopMessage" />
  </div>
</template>

<script setup>
import { ref, nextTick, watchEffect, onMounted, onUnmounted } from 'vue'
import ChatMessage from './ChatMessage.vue'
import ChatSendArea from './ChatSendArea.vue'
import { Apis } from './composables/useHttp'
import { useThrottleFn } from '@vueuse/core'
import { marked } from 'marked'
const emits = defineEmits(['questionFn'])

const props = defineProps({
  sessionId: String,
  onSendMessage: {
    type: Function,
    required: true
  }
})

const messages = ref([])
const loading = ref(false)
const hasMore = ref(false)
const scrollView = ref(null)
const sending = ref(false)
const sendAreaRef = ref(null)

const pageNum = ref(0)
const pageSize = ref(15)
const isRoller = ref(false)
onMounted(() => {
  scrollView.value.addEventListener('wheel', handleWheel)
})
// onUnmounted(() => {
//   // 组件卸载时移除事件监听
//   scrollView.value.removeEventListener("wheel", handleWheel);
// });

const handleWheel = (event) => {
  console.log('滚轮事件触发', event)
  if (!isRoller.value) {
    isRoller.value = true
  }
}

const onQuestion = (item) => {
  emits('questionFn', item)
}

const stopMessage = () => {
  Apis.stopOutput().then(() => {
    sending.value = false
  })
}

const loadMore = async () => {
  if (hasMore.value) {
    await loadHistoryMessage(pageNum.value + 1)
  }
}

const onScroll = useThrottleFn((event) => {
  if (event.target.scrollTop <= 300) {
    loadMore()
  }
})

const loadHistoryMessage = async (index = 0) => {
  console.log('--------------------')
  loading.value = true
  try {
    const { data } = await Apis.getHistoryChatContent(props.sessionId, index, pageSize.value)
    // let arr = [];
    // data.forEach((element) => {
    //   console.log("element", element);
    //   let obj = {
    //     chatid: element.chatid,
    //     chatpid: element.chatpid,
    //     chattime: element.chattime,
    //     data: marked(element.data),
    //     id: element.id,
    //     last_logging: element.last_logging,
    //     type: element.type,
    //     user_id: element.user_id,
    //   };
    //   arr.push(obj);
    // });
    pageNum.value = index
    if (index === 0) {
      messages.value = []
    }
    messages.value.unshift(...(data || []))
    hasMore.value = (data || []).length >= pageSize.value

    if (index === 0) {
      nextTick(() => {
        if (scrollView.value) {
          scrollView.value.scrollTo(0, scrollView.value.scrollHeight)
        }
      })
    }
    if ((messages.value[messages.value.length - 1].type = 'assist')) {
      let child = messages.value[messages.value.length - 1].chatid
      const { data } = await Apis.frequentlyAskedQuestions({ id: child })
      if (data && data.length > 0) {
        messages.value[messages.value.length - 1].issueData = data
        nextTick(() => {
          if (scrollView.value) {
            scrollView.value.scrollTo(0, scrollView.value.scrollHeight)
          }
        })
      }
    }
  } catch (err) {}
  loading.value = false
}

// const onSendMessage = ({ data, onMessage }) => {
//   console.log("---------");
//   return Apis.listenerAdviserMsg(data, onMessage);
// };
// 获取问题相关列表
// const getIssue = async ({ data, onMessage }) => {
//   return Apis.getSimilarProblems(data, onMessage);
//   // try {
//   //   const { data } = await Apis.getSimilarProblems();
//   //   let issueData = [];
//   //   if (data && data.length > 0) {
//   //     issueData = data;
//   //   }
//   //   return issueData;
//   // } catch (error) {
//   //   return [];
//   // }
// };
const makeUserSend = (message) => {
  return {
    data: message,
    type: 'user',
    chatid: Date.now()
  }
}

const isWriting = (index, { type }) => {
  return index === messages.value.length - 1 && sending.value && type === 'assist'
}

const sendMessage = async (value, params) => {
  isRoller.value = false
  sending.value = true
  const pid = messages.value[messages.value.length - 1]?.chatid
  const userMessage = makeUserSend(value)
  messages.value.push(userMessage)
  nextTick(() => {
    if (scrollView.value && !isRoller.value) {
      scrollView.value.scrollTo(0, scrollView.value.scrollHeight)
    }
  })
  try {
    let assistIndex = -1
    await props.onSendMessage({
      data: { ...params, query: value, pid },
      onMessage: (v) => {
        if (v.content) {
          // let messageContent = marked(v.content);
          if (assistIndex !== -1) {
            const now = { ...(messages.value[assistIndex] || {}) }
            now.data += v.content
            messages.value.splice(assistIndex, 1, now)
          } else {
            assistIndex = messages.value.length
            messages.value.push({
              data: v.content,
              type: 'assist',
              chatid: v.id
            })
          }
          nextTick(() => {
            if (scrollView.value && !isRoller.value) {
              scrollView.value.scrollTo(0, scrollView.value.scrollHeight)
            }
          })
        }
      }
    })

    // if ((messages.value[messages.value.length - 1].type = 'assist')) {
    //   let child = messages.value[messages.value.length - 1].chatid
    //   const { data } = await Apis.frequentlyAskedQuestions({ id: child })
    //   if (data && data.length > 0) {
    //     messages.value[messages.value.length - 1].issueData = data
    //     nextTick(() => {
    //       if (scrollView.value && !isRoller.value) {
    //         scrollView.value.scrollTo(0, scrollView.value.scrollHeight)
    //       }
    //     })
    //   }
    // }

    if (sendAreaRef.value) {
      sendAreaRef.value.clearInputMessage()
      console.log('messages', messages)
    }
  } catch (error) {
    console.log('error', error)
  }
  sending.value = false
}

watchEffect(
  () => {
    messages.value = []
    if (typeof props.sessionId !== 'undefined' && props.sessionId !== 'new') {
      // loadHistoryMessage()
    }
  },
  { flush: 'post' }
)

defineExpose({
  sendMessage
})
</script>

<style lang="less" scoped>
.chat-list {
  height: 100%;
  display: flex;
  flex-direction: column;

  .message-area {
    flex: 1;
    min-height: 0;
    // padding: 20px 39px 10px;
    box-sizing: border-box;
  }
  .scroll-view {
    overflow-y: auto;
    &::-webkit-scrollbar {
      width: 6px;
      background-color: transparent;
    }
    &::-webkit-scrollbar-thumb {
      border-radius: 6px;
      background-color: #ecebeb3d;
    }
  }
}
</style>
